<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>CtrlAssist</title>
    <link rel="icon" href="{{ url_for('static', filename='images/ctrlassist.png') }}" type="image/png">
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
    <script>
        function checkScreenSize() {
            const width = window.innerWidth;
            const height = window.innerHeight;
            console.log(`Screen width: ${width}, Screen height: ${height}`);
        }

        window.addEventListener('resize', checkScreenSize);
        window.addEventListener('load', checkScreenSize);

        function updateDateTime() {
            const now = new Date();
            document.getElementById('date-time').textContent = now.toLocaleString();
        }

        setInterval(updateDateTime, 1000);

        function fetchWeather() {
            fetch('https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=YOUR_LOCATION')
                .then(response => response.json())
                .then(data => {
                    document.getElementById('weather').textContent = `${data.current.temp_c}°C, ${data.current.condition.text}`;
                });
        }

        window.addEventListener('load', fetchWeather);
    </script>
</head>
<body>
    <div class="container">
        <h1>CtrlAssist</h1>
        <div class="dashboard">
            <div class="window" id="process-window">
                <h2>Processes</h2>
                <input type="text" id="process-search" placeholder="Search processes..." onkeyup="filterProcesses()">
                <ul id="process-list">
                    {% for process in processes %}
                        <li><a href="#" onclick="loadProcess({{ process['pid'] }})">{{ process['name'] }} (PID: {{ process['pid'] }})</a></li>
                    {% endfor %}
                </ul>
                <button onclick="refreshProcesses()">Refresh Processes</button>
            </div>
            <div class="window" id="scan-window">
                <h2>Memory Scanner</h2>
                <button onclick="attachProcess()">Attach to Selected Process</button>
                <br><br>

                <div class="scan-controls">
                    <label for="scan-type">Scan Type:</label>
                    <select id="scan-type" onchange="handleScanTypeChange()">
                        <option value="exact_value">Exact Value</option>
                        <option value="bigger_than">Bigger than...</option>
                        <option value="smaller_than">Smaller than...</option>
                        <option value="between">Value between...</option>
                        <option value="increased_value">Increased Value</option>
                        <option value="increased_by">Increased by...</option>
                        <option value="decreased_value">Decreased Value</option>
                        <option value="decreased_by">Decreased by...</option>
                        <option value="changed_value">Changed Value</option>
                        <option value="unchanged_value">Unchanged Value</option>
                        <option value="unknown_initial">Unknown Initial Value</option>
                    </select>

                    <div id="value-inputs">
                        <input type="text" id="scan-value1" placeholder="Value" style="width:80px">
                        <input type="text" id="scan-value2" placeholder="to" style="width:60px; display:none">
                    </div>

                    <label for="value-type">Value Type:</label>
                    <select id="value-type">
                        <option value="binary">Binary</option>
                        <option value="byte">Byte</option>
                        <option value="2bytes">2 Bytes</option>
                        <option value="4bytes" selected>4 Bytes</option>
                        <option value="8bytes">8 Bytes</option>
                        <option value="float">Float</option>
                        <option value="double">Double</option>
                        <option value="string">String</option>
                        <option value="byte_array">Byte Array</option>
                        <option value="all_types">All Types</option>
                        <option value="group">Group</option>
                    </select>
                </div>

                <div class="scan-buttons">
                    <button onclick="firstScan()">First Scan</button>
                    <button onclick="nextScan()" id="next-scan-btn" disabled>Next Scan</button>
                    <button onclick="undoScan()" id="undo-scan-btn" disabled>Undo Scan</button>
                    <button onclick="resetScan()">New Scan</button>
                </div>

                <div class="scan-options-toggle">
                    <button onclick="toggleScanOptions()" id="options-toggle">▼ Scan Options</button>
                </div>

                <div id="scan-options" style="display:none; border:1px solid #ccc; padding:10px; margin:5px 0;">
                    <div style="display:flex; flex-wrap:wrap; gap:10px; font-size:12px;">
                        <div>
                            <label>Start: </label>
                            <input type="text" id="start-address" value="00000000" style="width:80px">
                        </div>
                        <div>
                            <label>Stop: </label>
                            <input type="text" id="stop-address" value="7FFFFFFF" style="width:80px">
                        </div>
                        <div>
                            <label><input type="checkbox" id="readable" checked> Readable</label>
                        </div>
                        <div>
                            <label><input type="checkbox" id="writable" checked> Writable</label>
                        </div>
                        <div>
                            <label><input type="checkbox" id="executable" checked> Executable</label>
                        </div>
                        <div>
                            <label><input type="checkbox" id="copy-on-write"> Copy on Write</label>
                        </div>
                        <div>
                            <label><input type="checkbox" id="fast-scan" checked> Fast Scan</label>
                        </div>
                        <div>
                            <label>Alignment: </label>
                            <input type="number" id="alignment" value="1" min="1" style="width:50px">
                        </div>
                        <div>
                            <label>Last Digits: </label>
                            <input type="number" id="last-digits" value="0" min="0" style="width:50px">
                        </div>
                    </div>
                </div>

                <div id="scan-status" style="margin:10px 0; font-weight:bold;"></div>

                <div class="scan-results-section">
                    <button onclick="viewScanResults()" id="view-results-btn" disabled>View Results (0)</button>
                    <button onclick="updateResults()" id="update-results-btn" disabled>Update Values</button>
                </div>

                <div id="scan-results-display" style="display:none; max-height:200px; overflow-y:auto; border:1px solid #ccc; margin:5px 0;">
                    <div style="font-weight:bold; padding:5px; border-bottom:1px solid #ccc; font-size:11px;">
                        Address | Current Value | Previous Value
                    </div>
                    <div id="results-list" style="font-family:monospace; font-size:10px;"></div>
                </div>
            </div>
            <div class="window" id="modify-window">
                <h2>Memory Editor</h2>
                <input type="text" id="memory-address" placeholder="Memory Address (hex)">
                <input type="text" id="memory-value" placeholder="New Value">
                <select id="modify-type">
                    <option value="byte">Byte</option>
                    <option value="2bytes">2 Bytes</option>
                    <option value="4bytes" selected>4 Bytes</option>
                    <option value="8bytes">8 Bytes</option>
                    <option value="float">Float</option>
                    <option value="double">Double</option>
                    <option value="string">String</option>
                </select>
                <button onclick="modifyMemory()">Write Memory</button>
            </div>
            <div class="window" id="control-window">
                <h2>Game Speed Control</h2>
                <label for="game-speed">Speed Multiplier:</label>
                <input type="range" id="game-speed" min="0.1" max="5" step="0.1" value="1" oninput="updateSpeedValue(this.value)">
                <span id="speed-value">1.0x</span>
                <button onclick="changeGameSpeed()">Apply Speed</button>
                <button onclick="resetSpeed()">Unload DLL</button>
            </div>
            <div class="window" id="offset-window">
                <h2>Offset Calculator</h2>
                <input type="text" id="module-name" placeholder="Module name (e.g., game.exe)">
                <button onclick="getModuleBase()">Get Base Address</button>
                <div id="base-address"></div>
                <br>
                <input type="text" id="base-addr" placeholder="Base Address (hex)">
                <input type="text" id="target-addr" placeholder="Target Address (hex)">
                <button onclick="calculateOffset()">Calculate Offset</button>
                <div id="offset-result"></div>
            </div>
            <div class="window" id="pointer-window">
                <h2>Pointer Scanner</h2>
                <input type="text" id="pointer-base" placeholder="Base Address (hex)">
                <input type="text" id="pointer-offsets" placeholder="Offsets (comma separated, hex)">
                <button onclick="resolvePointer()">Resolve Pointer Chain</button>
                <div id="pointer-result"></div>
            </div>
            <div class="window" id="jvm-window">
                <h2>JVM Detection</h2>
                <button onclick="detectJVM()">Detect JVM Processes</button>
                <button onclick="refreshJVM()">Refresh JVM</button>
                <div id="jvm-results"></div>
            </div>
            <div class="window" id="network-window">
                <h2>Network Analyzer</h2>
                <div class="network-controls">
                    <button onclick="hookProcess()">Hook Process</button>
                    <button onclick="unhookProcess()">Unhook</button>
                    <button onclick="startPacketCapture()">Start Capture</button>
                    <button onclick="stopPacketCapture()">Stop</button>
                    <button onclick="clearPackets()">Clear</button>
                    <button onclick="getNetworkStats()">Statistics</button>
                </div>
                <div class="network-filters">
                    <select id="protocol-filter" onchange="setNetworkFilter('protocol', this.value)">
                        <option value="all">All Protocols</option>
                        <option value="tcp">TCP</option>
                        <option value="udp">UDP</option>
                        <option value="icmp">ICMP</option>
                    </select>
                    <input type="text" id="port-filter" placeholder="Port" onchange="setNetworkFilter('port', this.value)" style="width:60px">
                    <input type="text" id="ip-filter" placeholder="IP Address" onchange="setNetworkFilter('ip', this.value)" style="width:100px">
                </div>
                <div id="hooked-process-info" style="font-size:11px; margin:5px 0; color:#0066cc;"></div>
                <div id="network-stats" style="font-size:11px; margin:5px 0;"></div>
                <div id="packet-results" style="max-height:250px; overflow-y:auto; font-family:monospace; font-size:10px;"></div>
            </div>
            <div class="window" id="overlay-window">
                <h2>Visual Overlay</h2>
                <button onclick="startOverlay()">Start Overlay</button>
                <button onclick="stopOverlay()">Stop Overlay</button>
                <br><br>
                <input type="number" id="box-x" placeholder="X" style="width:60px">
                <input type="number" id="box-y" placeholder="Y" style="width:60px">
                <input type="number" id="box-width" placeholder="Width" style="width:60px">
                <input type="number" id="box-height" placeholder="Height" style="width:60px">
                <select id="box-color">
                    <option value="red">Red</option>
                    <option value="green">Green</option>
                    <option value="blue">Blue</option>
                    <option value="yellow">Yellow</option>
                    <option value="white">White</option>
                </select>
                <button onclick="drawBox()">Draw Box</button>
                <button onclick="clearOverlay()">Clear All</button>
            </div>
            <div class="window" id="control-panel">
                <h2>Control Panel</h2>
                <button onclick="checkForUpdates()">Check for Updates</button>
                <div id="update-status"></div>
                <button onclick="exitApplication()" style="background-color: #dc3545;">Exit Application</button>
            </div>
        </div>
        <div class="status-bar">
            <div id="date-time"></div>
            <div id="weather"></div>
            <div id="system-status">
                <div id="cpu-status">CPU: </div>
                <div id="gpu-status">GPU: </div>
                <div id="memory-status">Memory: </div>
                <div id="disk-status">Disk: </div>
            </div>
            <div id="selected-process">Selected Process: None</div>
            <div id="company-name">SPIKE LLC</div>
        </div>
    </div>

    <script>
        let selectedPid = null;

        function loadProcess(pid) {
            selectedPid = pid;  // 保存选中的PID

            // 高亮显示选中的进程
            const processList = document.getElementById('process-list');
            const items = processList.getElementsByTagName('li');
            for (let item of items) {
                item.classList.remove('selected');
                if (item.textContent.includes(`PID: ${pid}`)) {
                    item.classList.add('selected');
                }
            }

            // 获取进程信息
            fetch(`/process/${pid}`)
                .then(response => response.json())
                .then(data => {
                    if (data.error) {
                        showError(data.error);
                        return;
                    }

                    // 更新UI显示进程信息
                    document.getElementById('scan-status').innerHTML =
                        `Selected process: ${data.name} (PID: ${data.pid})<br>` +
                        `CPU: ${data.cpu_usage}% | Memory: ${data.memory_usage}%`;

                    // 更新底部状态栏
                    document.getElementById('selected-process').textContent =
                        `Selected Process: ${data.name} (PID: ${data.pid})`;

                    // 更新系统状态信息
                    document.getElementById('cpu-status').textContent = `CPU: ${data.cpu_usage}%`;
                    document.getElementById('memory-status').textContent = `Memory: ${data.memory_usage}%`;
                    if (data.disk_usage) {
                        document.getElementById('disk-status').textContent = `Disk: ${data.disk_usage}%`;
                    }

                    // 启用扫描按钮
                    document.getElementById('next-scan-btn').disabled = true;
                    document.getElementById('undo-scan-btn').disabled = true;
                    document.getElementById('view-results-btn').disabled = true;
                    document.getElementById('update-results-btn').disabled = true;
                })
                .catch(error => {
                    showError('Failed to load process information');
                    console.error('Error:', error);
                });
        }

        function showError(message) {
            const status = document.getElementById('scan-status');
            status.innerHTML = `<span style="color: red;">${message}</span>`;
        }

        function attachProcess() {
            if (!selectedPid) {
                showError('Please select a process first');
                return;
            }

            fetch('/attach_process', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ pid: selectedPid })
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    document.getElementById('scan-status').innerHTML =
                        `<span style="color: green;">${data.message}</span>`;
                } else {
                    showError(data.message);
                }
            })
            .catch(error => {
                showError('Failed to attach to process');
                console.error('Error:', error);
            });
        }

        let scanResultsVisible = false;
        let currentScanCount = 0;

        function handleScanTypeChange() {
            const scanType = document.getElementById('scan-type').value;
            const value2Input = document.getElementById('scan-value2');
            const value1Input = document.getElementById('scan-value1');

            // Show/hide second value input for "between" scan type
            if (scanType === 'between') {
                value2Input.style.display = 'inline';
                value1Input.placeholder = 'From';
            } else {
                value2Input.style.display = 'none';
                value1Input.placeholder = getPlaceholderForScanType(scanType);
            }

            // Hide value inputs for certain scan types
            const noValueTypes = ['increased_value', 'decreased_value', 'changed_value', 'unchanged_value', 'unknown_initial'];
            const valueInputsDiv = document.getElementById('value-inputs');
            if (noValueTypes.includes(scanType)) {
                valueInputsDiv.style.display = 'none';
            } else {
                valueInputsDiv.style.display = 'inline';
            }
        }

        function getPlaceholderForScanType(scanType) {
            const placeholders = {
                'exact_value': 'Value',
                'bigger_than': 'Value',
                'smaller_than': 'Value',
                'increased_by': 'Amount',
                'decreased_by': 'Amount'
            };
            return placeholders[scanType] || 'Value';
        }

        function toggleScanOptions() {
            const optionsDiv = document.getElementById('scan-options');
            const toggleBtn = document.getElementById('options-toggle');

            if (optionsDiv.style.display === 'none') {
                optionsDiv.style.display = 'block';
                toggleBtn.textContent = '▲ Scan Options';
            } else {
                optionsDiv.style.display = 'none';
                toggleBtn.textContent = '▼ Scan Options';
            }
        }

        function firstScan() {
            const scanType = document.getElementById('scan-type').value;
            const valueType = document.getElementById('value-type').value;
            const value1 = document.getElementById('scan-value1').value;
            const value2 = document.getElementById('scan-value2').value;

            // Validate inputs
            const noValueTypes = ['increased_value', 'decreased_value', 'changed_value', 'unchanged_value', 'unknown_initial'];
            if (!noValueTypes.includes(scanType) && !value1) {
                alert('Please enter a value to scan');
                return;
            }

            if (scanType === 'between' && (!value1 || !value2)) {
                alert('Please enter both values for range scan');
                return;
            }

            // Set scan options
            setScanOptions();

            document.getElementById('scan-status').textContent = 'First scan in progress...';

            fetch('/first_scan', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    scanType,
                    valueType,
                    value1: value1 || null,
                    value2: value2 || null
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    document.getElementById('scan-status').textContent = `Error: ${data.error}`;
                    return;
                }

                currentScanCount = data.count;
                document.getElementById('scan-status').textContent = `First scan completed. Found ${data.count} results.`;
                document.getElementById('view-results-btn').textContent = `View Results (${data.count})`;

                // Enable buttons
                document.getElementById('next-scan-btn').disabled = data.count === 0;
                document.getElementById('undo-scan-btn').disabled = false;
                document.getElementById('view-results-btn').disabled = data.count === 0;
                document.getElementById('update-results-btn').disabled = data.count === 0;
            })
            .catch(error => {
                console.error('Error:', error);
                document.getElementById('scan-status').textContent = 'First scan failed';
            });
        }

        function nextScan() {
            const scanType = document.getElementById('scan-type').value;
            const valueType = document.getElementById('value-type').value;
            const value1 = document.getElementById('scan-value1').value;
            const value2 = document.getElementById('scan-value2').value;

            if (currentScanCount === 0) {
                alert('No previous scan results to filter');
                return;
            }

            // Validate inputs
            const noValueTypes = ['increased_value', 'decreased_value', 'changed_value', 'unchanged_value'];
            if (!noValueTypes.includes(scanType) && !value1) {
                alert('Please enter a value to scan');
                return;
            }

            document.getElementById('scan-status').textContent = `Next scan in progress (filtering ${currentScanCount} results)...`;

            fetch('/next_scan', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    scanType,
                    valueType,
                    value1: value1 || null,
                    value2: value2 || null
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    document.getElementById('scan-status').textContent = `Error: ${data.error}`;
                    return;
                }

                currentScanCount = data.count;
                document.getElementById('scan-status').textContent = `Next scan completed. Found ${data.count} results.`;
                document.getElementById('view-results-btn').textContent = `View Results (${data.count})`;

                // Update buttons
                document.getElementById('next-scan-btn').disabled = data.count === 0;
                document.getElementById('view-results-btn').disabled = data.count === 0;
                document.getElementById('update-results-btn').disabled = data.count === 0;

                // Update results display if visible
                if (scanResultsVisible) {
                    viewScanResults();
                }
            })
            .catch(error => {
                console.error('Error:', error);
                document.getElementById('scan-status').textContent = 'Next scan failed';
            });
        }

        function undoScan() {
            fetch('/undo_scan', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' }
            })
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    alert('Cannot undo scan: ' + data.error);
                    return;
                }

                document.getElementById('scan-status').textContent = 'Scan undone.';
                // Note: In a full implementation, we'd need to track scan history to restore count
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Failed to undo scan');
            });
        }

        function setScanOptions() {
            const options = {
                start_address: document.getElementById('start-address').value,
                stop_address: document.getElementById('stop-address').value,
                readable: document.getElementById('readable').checked,
                writable: document.getElementById('writable').checked,
                executable: document.getElementById('executable').checked,
                copy_on_write: document.getElementById('copy-on-write').checked,
                fast_scan: document.getElementById('fast-scan').checked,
                alignment: document.getElementById('alignment').value,
                last_digits: document.getElementById('last-digits').value
            };

            fetch('/set_scan_options', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(options)
            });
        }

        function viewScanResults() {
            const resultsDisplay = document.getElementById('scan-results-display');
            const valueType = document.getElementById('value-type').value;

            if (scanResultsVisible) {
                resultsDisplay.style.display = 'none';
                scanResultsVisible = false;
                document.getElementById('view-results-btn').textContent = `View Results (${currentScanCount})`;
                return;
            }

            // 增加分页控制
            let currentPage = 0;
            const pageSize = 1000;  // 增加每页显示的数量

            function loadPage(page) {
                const start = page * pageSize;
                fetch(`/get_scan_results?start=${start}&count=${pageSize}`)
                    .then(response => response.json())
                    .then(data => {
                        if (data.error) {
                            alert('Error loading results: ' + data.error);
                            return;
                        }

                        const resultsList = document.getElementById('results-list');
                        if (page === 0) {
                            resultsList.innerHTML = '';
                        }

                        data.results.forEach(result => {
                            const div = document.createElement('div');
                            div.style.padding = '2px 5px';
                            div.style.borderBottom = '1px solid #eee';
                            div.style.cursor = 'pointer';

                            // 格式化显示值，保留previous_value的显示
                            let currentValue = result.current_value;
                            let previousValue = result.previous_value;

                            if (valueType === 'float' || valueType === 'double') {
                                currentValue = parseFloat(currentValue).toFixed(6);
                                if (previousValue !== null && previousValue !== 'N/A') {
                                    previousValue = parseFloat(previousValue).toFixed(6);
                                }
                            }

                            div.innerHTML = `${result.address} | ${currentValue} | ${previousValue === null ? 'N/A' : previousValue}`;

                            div.onclick = () => {
                                document.getElementById('memory-address').value = result.address;
                                document.getElementById('memory-value').value = currentValue;
                            };

                            resultsList.appendChild(div);
                        });

                        if (data.results.length === pageSize) {
                            currentPage++;
                            loadPage(currentPage);  // 自动加载下一页
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        alert('Failed to load scan results');
                    });
            }

            resultsDisplay.style.display = 'block';
            scanResultsVisible = true;
            document.getElementById('view-results-btn').textContent = `Hide Results (${currentScanCount})`;

            // 开始加载第一页
            loadPage(0);
        }

        function updateResults() {
            const valueType = document.getElementById('value-type').value;

            fetch('/update_scan_results', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ valueType })
            })
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    alert('Error updating results: ' + data.error);
                    return;
                }

                document.getElementById('scan-status').textContent = `Updated ${data.updated} values.`;

                // Refresh results display if visible
                if (scanResultsVisible) {
                    viewScanResults();
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Failed to update results');
            });
        }

        function resetScan() {
            currentScanCount = 0;
            scanResultsVisible = false;

            document.getElementById('scan-status').textContent = '';
            document.getElementById('scan-value1').value = '';
            document.getElementById('scan-value2').value = '';
            document.getElementById('scan-results-display').style.display = 'none';

            // Reset buttons
            document.getElementById('next-scan-btn').disabled = true;
            document.getElementById('undo-scan-btn').disabled = true;
            document.getElementById('view-results-btn').disabled = true;
            document.getElementById('view-results-btn').textContent = 'View Results (0)';
            document.getElementById('update-results-btn').disabled = true;
        }

        function modifyMemory() {
            const address = document.getElementById('memory-address').value;
            const value = document.getElementById('memory-value').value;
            const valueType = document.getElementById('modify-type').value;

            if (!address || !value) {
                alert('Please enter both address and value');
                return;
            }

            fetch('/modify_memory', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ address, value, valueType })
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    alert('Memory modified successfully');
                } else {
                    alert(`Failed to modify memory: ${data.error}`);
                }
            });
        }

        // Initialize scan type change handler
        document.addEventListener('DOMContentLoaded', function() {
            handleScanTypeChange();
        });

        function refreshProcesses() {
            fetch('/refresh_processes')
                .then(response => response.json())
                .then(data => {  // 这里修复了语法错误
                    const processList = document.getElementById('process-list');
                    processList.innerHTML = '';
                    data.processes.forEach(process => {
                        const li = document.createElement('li');
                        li.innerHTML = `<a href="#" onclick="loadProcess(${process.pid})">${process.name} (PID: ${process.pid})</a>`;
                        processList.appendChild(li);
                    });

                    // 如果之前选中的进程还在列表中，保持其选中状态
                    if (selectedPid) {
                        const items = processList.getElementsByTagName('li');
                        for (let item of items) {
                            if (item.textContent.includes(`PID: ${selectedPid}`)) {
                                item.classList.add('selected');
                            }
                        }
                    }
                })
                .catch(error => {
                    console.error('Error refreshing processes:', error);
                    location.reload(); // Fallback to page reload
                });
        }
        
        function refreshJVM() {
            detectJVM();
        }
        
        function filterProcesses() {
            const searchTerm = document.getElementById('process-search').value.toLowerCase();
            const processList = document.getElementById('process-list');
            const processes = processList.getElementsByTagName('li');
            
            for (let i = 0; i < processes.length; i++) {
                const processText = processes[i].textContent.toLowerCase();
                if (processText.includes(searchTerm)) {
                    processes[i].style.display = '';
                } else {
                    processes[i].style.display = 'none';
                }
            }
        }

        function updateSpeedValue(value) {
            document.getElementById('speed-value').textContent = value + 'x';
        }

        function changeGameSpeed() {
            if (!selectedPid) {
                alert('Please select a process first');
                return;
            }
            
            const speed = document.getElementById('game-speed').value;
            
            fetch('/change_speed', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ pid: selectedPid, speed })
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    alert(data.message);
                } else {
                    alert(`Failed to change speed: ${data.error}`);
                }
            });
        }
        
        function resetSpeed() {
            if (!selectedPid) {
                alert('Please select a process first');
                return;
            }
            
            fetch('/reset_speed', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ pid: selectedPid })
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    document.getElementById('game-speed').value = 1.0;
                    document.getElementById('speed-value').textContent = '1.0x';
                    alert(data.message);
                } else {
                    alert(`Failed to reset speed: ${data.error}`);
                }
            });
        }
        
        function getModuleBase() {
            const moduleName = document.getElementById('module-name').value;
            if (!moduleName) {
                alert('Please enter module name');
                return;
            }
            
            fetch('/get_module_base', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ moduleName })
            })
            .then(response => response.json())
            .then(data => {
                if (data.baseAddress) {
                    document.getElementById('base-address').textContent = `Base: ${data.baseAddress}`;
                    document.getElementById('base-addr').value = data.baseAddress;
                } else {
                    alert('Module not found');
                }
            });
        }
        
        function calculateOffset() {
            const baseAddr = document.getElementById('base-addr').value;
            const targetAddr = document.getElementById('target-addr').value;
            
            if (!baseAddr || !targetAddr) {
                alert('Please enter both addresses');
                return;
            }
            
            fetch('/calculate_offset', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ baseAddress: baseAddr, targetAddress: targetAddr })
            })
            .then(response => response.json())
            .then(data => {
                document.getElementById('offset-result').textContent = `Offset: ${data.offset}`;
            });
        }
        
        function resolvePointer() {
            const baseAddr = document.getElementById('pointer-base').value;
            const offsetsStr = document.getElementById('pointer-offsets').value;
            
            if (!baseAddr || !offsetsStr) {
                alert('Please enter base address and offsets');
                return;
            }
            
            const offsets = offsetsStr.split(',').map(s => s.trim());
            
            fetch('/resolve_pointer', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ baseAddress: baseAddr, offsets })
            })
            .then(response => response.json())
            .then(data => {
                if (data.finalAddress) {
                    document.getElementById('pointer-result').textContent = `Final Address: ${data.finalAddress}`;
                } else {
                    alert('Failed to resolve pointer chain');
                }
            });
        }
        
        function detectJVM() {
            fetch('/detect_jvm', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' }
            })
            .then(response => response.json())
            .then(data => {
                const resultsDiv = document.getElementById('jvm-results');
                resultsDiv.innerHTML = '';
                
                if (data.jvmProcesses && data.jvmProcesses.length > 0) {
                    data.jvmProcesses.forEach(proc => {
                        const div = document.createElement('div');
                        div.innerHTML = `<strong>${proc.name}</strong> (PID: ${proc.pid})<br>Main Class: ${proc.main_class}`;
                        div.style.padding = '5px';
                        div.style.borderBottom = '1px solid #eee';
                        resultsDiv.appendChild(div);
                    });
                } else {
                    resultsDiv.textContent = 'No JVM processes found';
                }
            });
        }
        
        function checkForUpdates() {
            const statusDiv = document.getElementById('update-status');
            statusDiv.textContent = 'Checking for updates...';
            
            fetch('https://api.github.com/repos/spikego/CtrlAssist/releases/latest')
                .then(response => response.json())
                .then(data => {
                    statusDiv.innerHTML = `Latest: ${data.tag_name}<br><a href="${data.html_url}" target="_blank">Download</a>`;
                })
                .catch(() => {
                    statusDiv.textContent = 'Failed to check for updates';
                });
        }
        
        let captureInterval = null;
        
        function hookProcess() {
            if (!selectedPid) {
                alert('Please select a process first');
                return;
            }
            
            fetch('/hook_process', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ pid: selectedPid })
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    document.getElementById('hooked-process-info').innerHTML = `<strong>Hooked Process:</strong> PID ${selectedPid}`;
                    updateHookedProcessInfo();
                } else {
                    alert('Failed to hook process: ' + data.error);
                }
            });
        }
        
        function unhookProcess() {
            fetch('/unhook_process', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' }
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    document.getElementById('hooked-process-info').innerHTML = '';
                }
            });
        }
        
        function updateHookedProcessInfo() {
            fetch('/get_hooked_process_info')
                .then(response => response.json())
                .then(data => {
                    if (data.processInfo && data.processInfo.pid) {
                        const info = data.processInfo;
                        document.getElementById('hooked-process-info').innerHTML = 
                            `<strong>Hooked:</strong> ${info.name} (PID: ${info.pid}) | Connections: ${info.connections_count || 0} | CPU: ${info.cpu_percent || 0}%`;
                    }
                });
        }
        
        function startPacketCapture() {
            const hookedPid = document.getElementById('hooked-process-info').innerHTML.includes('PID') ? selectedPid : null;
            
            fetch('/start_packet_capture', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ pid: hookedPid })
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    const message = hookedPid ? `Packet capture started for PID ${hookedPid}` : 'Packet capture started (all processes)';
                    document.getElementById('packet-results').innerHTML = `<div style="color:green;">${message}</div>`;
                    captureInterval = setInterval(getPackets, 2000);
                }
            });
        }
        
        function stopPacketCapture() {
            fetch('/stop_packet_capture', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' }
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    if (captureInterval) {
                        clearInterval(captureInterval);
                        captureInterval = null;
                    }
                    document.getElementById('packet-results').innerHTML += '<div style="color:red;">Packet capture stopped.</div>';
                }
            });
        }
        
        function clearPackets() {
            fetch('/clear_packets', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' }
            })
            .then(() => {
                document.getElementById('packet-results').innerHTML = '';
                document.getElementById('network-stats').innerHTML = '';
            });
        }
        
        function getPackets() {
            fetch('/get_packets')
                .then(response => response.json())
                .then(data => {
                    const resultsDiv = document.getElementById('packet-results');
                    const statsDiv = document.getElementById('network-stats');
                    
                    // Update hooked process info if available
                    if (data.hookedProcess && data.hookedProcess.pid) {
                        updateHookedProcessInfo();
                    }
                    
                    // Update statistics
                    if (data.stats) {
                        const stats = data.stats;
                        statsDiv.innerHTML = `Packets: ${stats.total_packets || 0} | Bytes: ${stats.total_bytes || 0} | Protocols: ${Object.keys(stats.protocols || {}).join(', ')}`;
                    }
                    
                    // Update packet list (show only recent packets)
                    if (data.packets && data.packets.length > 0) {
                        resultsDiv.innerHTML = ''; // Clear previous
                        
                        // Create header
                        const header = document.createElement('div');
                        header.innerHTML = 'No. | Time | Source | Destination | Protocol | Length | Info';
                        header.style.fontWeight = 'bold';
                        header.style.borderBottom = '2px solid #333';
                        header.style.padding = '2px';
                        resultsDiv.appendChild(header);
                        
                        // Show last 20 packets
                        const recentPackets = data.packets.slice(-20);
                        recentPackets.forEach(packet => {
                            const div = document.createElement('div');
                            div.innerHTML = `${packet.no || 0} | ${packet.time} | ${packet.src}:${packet.src_port || ''} | ${packet.dst}:${packet.dst_port || ''} | ${packet.protocol} | ${packet.length || 0} | ${packet.info || ''}`;
                            div.style.padding = '1px';
                            div.style.borderBottom = '1px solid #eee';
                            div.style.cursor = 'pointer';
                            div.title = `Raw data: ${packet.raw_data || 'N/A'}`;
                            
                            // Highlight packets from hooked process
                            if (packet.pid) {
                                div.style.backgroundColor = '#e6f3ff';
                            }
                            
                            div.onclick = () => {
                                let details = `Packet Details:\nNo: ${packet.no}\nTime: ${packet.time}\nSource: ${packet.src}:${packet.src_port || 'N/A'}\nDestination: ${packet.dst}:${packet.dst_port || 'N/A'}\nProtocol: ${packet.protocol}\nLength: ${packet.length}\nTTL: ${packet.ttl || 'N/A'}\nFlags: ${packet.flags || 'N/A'}\nInfo: ${packet.info}`;
                                if (packet.pid) {
                                    details += `\nProcess PID: ${packet.pid}`;
                                }
                                details += `\nRaw Data: ${packet.raw_data || 'N/A'}`;
                                alert(details);
                            };
                            resultsDiv.appendChild(div);
                        });
                    }
                });
        }
        
        function setNetworkFilter(type, value) {
            fetch('/set_network_filter', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ type: type, value: value })
            });
        }
        
        function getNetworkStats() {
            fetch('/get_network_stats')
                .then(response => response.json())
                .then(data => {
                    if (data.stats) {
                        const stats = data.stats;
                        let statsText = `Network Statistics:\n`;
                        statsText += `Total Packets: ${stats.total_packets || 0}\n`;
                        statsText += `Total Bytes: ${stats.total_bytes || 0}\n`;
                        statsText += `Capture Time: ${Math.round(stats.capture_time || 0)}s\n`;
                        statsText += `Protocols:\n`;
                        for (const [protocol, count] of Object.entries(stats.protocols || {})) {
                            statsText += `  ${protocol}: ${count}\n`;
                        }
                        alert(statsText);
                    }
                });
        }
        
        function startOverlay() {
            if (!selectedPid) {
                alert('Please select a process first');
                return;
            }
            
            fetch('/start_overlay', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ pid: selectedPid })
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    alert('Overlay started');
                } else {
                    alert('Failed to start overlay');
                }
            });
        }
        
        function stopOverlay() {
            fetch('/stop_overlay', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' }
            })
            .then(response => response.json())
            .then(data => {
                alert('Overlay stopped');
            });
        }
        
        function drawBox() {
            const x = document.getElementById('box-x').value;
            const y = document.getElementById('box-y').value;
            const width = document.getElementById('box-width').value;
            const height = document.getElementById('box-height').value;
            const color = document.getElementById('box-color').value;
            
            if (!x || !y || !width || !height) {
                alert('Please enter all box parameters');
                return;
            }
            
            fetch('/draw_box', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ x, y, width, height, color })
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    console.log('Box drawn');
                }
            });
        }
        
        function clearOverlay() {
            fetch('/clear_overlay', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' }
            })
            .then(response => response.json())
            .then(data => {
                console.log('Overlay cleared');
            });
        }
        
        function exitApplication() {
            if (confirm('Are you sure you want to exit CtrlAssist?')) {
                fetch('/exit_app', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' }
                })
                .then(() => {
                    window.close();
                })
                .catch(() => {
                    window.close();
                });
            }
        }
    </script>
</body>
</html>

